package es.esa.integral;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by esalazar on 4/28/14.
 */
public class SimbadService {

    private static SimbadService instance = null;
    private static final String URL="http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=%s";

    private SimbadService() {};

    public static SimbadService getInstance() {
        if (instance == null) {
            instance = new SimbadService();
        }
        return instance;
    }

    public SimbadInformationBean useRESTWebService(String sourceName) {
        java.net.URL url;
        try {
            url = new URL(String.format(URL, URLEncoder.encode(sourceName, "UTF-8")));

            HttpURLConnection hc = (HttpURLConnection) url.openConnection();
            hc.setRequestMethod("GET");
            hc.setDoInput(true);
            hc.setDoOutput(true);
            hc.setUseCaches(false);
            hc.connect();
            InputStreamReader in = new InputStreamReader((InputStream) hc
                    .getContent());
            BufferedReader buff = new BufferedReader(new InputStreamReader((InputStream) hc
                    .getContent()));
            String line ="";
            String objectId = "";
            SimbadInformationBean info = new SimbadInformationBean();
            info.setName(sourceName);
            while ((line = buff.readLine()) != null){
                if (line.contains("OID=@")) {
                    line =line.substring(line.indexOf("OID=@") + "OID=@".length());
                    objectId = line.substring(0, line.indexOf(" "));
                } else if (line.contains("No known catalog") || line.contains("Identifier not found in the database")) {
                    //throw new RuntimeException("Source '" + sourceName + "' not found in Simbad, NED and VizieR");
                    SimbadInformationBean infoNotAvailable = new SimbadInformationBean();
                    infoNotAvailable.setObjectId("-1");
                    return infoNotAvailable;
                } else if (line.contains("Coordinates(Gal,ep=J2000,eq=2000):")){
                    line = line.substring(line.lastIndexOf(":")+2);
                    String raString = line.substring(0 , line.indexOf(" "));
                    line = line.substring(line.indexOf(" ")+2);
                    double ra = Double.valueOf(raString);
                    String decString = line.substring(0 , line.indexOf(" "));
                    double dec= Double.valueOf(decString);
                    info.setPosition(new Position(ra, dec));
                } else if (line.contains("Identifiers")){
                    int length = 32;
                    while ((line = buff.readLine()) != null && line.equals("") == false) {
                        String first = removeBlank(line.substring(3,length));
                        info.getAliases().add(first);
                        if (line.length() >= 3 + 2*length) {
                            String second = removeBlank(line.substring(3 + length, 3 + 2*length));
                            if (second.length()>0)
                                info.getAliases().add(second);
                            String third = removeBlank(line.substring(3 + 2*length));
                            if (third.length()>0)
                                info.getAliases().add(third);

                        }

                    }

                }
            }

            if (objectId == "") throw new RuntimeException("The service was not able to provide information for " +sourceName );
            info.setObjectId(objectId);
            buff.close();
            in.close();
            hc.disconnect();
            return info;

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static String removeBlank(String st) {
        if (st.contains(" ") == false) return st;
        if (st.substring(st.length()-1).startsWith(" ")) {
            return removeBlank(st.substring(0, st.length()-1));
        }
        return st;
    }
}
